package com.harry.broadreceiverstart;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import java.lang.ref.WeakReference;

/**
 * @author Martin-harry
 * @date 2022/3/2
 * @address
 * @Desc 解决Handler内存泄漏
 */
public class MainActivity extends Activity {

    private static final String tag = "MainActivity";
    private TextView mTvShow;
    private MyHandler mHandler;
    private static final int DELAY_TIME = 10000; // set to 5s and 10s to check result.

    /**
     * 声明Handler为static并持有Activity的弱引用
     */
    static class MyHandler extends Handler {
        WeakReference mWeakActivity;

        public MyHandler(MainActivity activity) {

            mWeakActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            MainActivity activity = (MainActivity) mWeakActivity.get();

            Log.e(tag, "handleMessage," + msg.what);

// 5s is not null, 10s is null, tell that activity is recycled.
            if (null != activity) {
                if(msg.what == 1 ){
                    Log.e(tag, "not null");

                    activity.mTvShow.setText("delay show");
                }
            }
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mHandler = new MyHandler(MainActivity.this);

        Log.e(tag, "onCreate");

        mTvShow = (TextView) findViewById(R.id.tv_show);

        new Thread() {
            @Override
            public void run() {

                mHandler.sendEmptyMessageDelayed(1, DELAY_TIME);
                Log.e(tag, "msg send");
            }
        }.start();
    }


    /**
     * onDestroy时清除消息
     * mHandler.removeCallbacksAndMessages(null); // 參数为null时会清除全部消息。
     */
    @Override
    protected void onDestroy() {

        Log.e(tag, "onDestroy");

        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
    }

}
